package cn.andy.android.crm.adapter;

import java.util.List;

import cn.andy.android.crm.R;
import cn.andy.android.crm.beans.PersonInfo;
import cn.andy.android.crm.db.PersonDBHelper;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;

public class MyAdapter extends BaseAdapter{
	
	public List<PersonInfo> arrays = null;
	private Context context;
	private Button curbutton;
	private float x, ux;
	private PersonDBHelper helper;
	public int selectedpos = -1;
	
	public MyAdapter(Context context, List<PersonInfo> arrays, PersonDBHelper helper){
		this.context = context;
		this.arrays = arrays;
		this.helper = helper;
	}

	public int getCount() {
		return this.arrays.size();
	}

	public Object getItem(int position) {
		return this.arrays.get(position);
	}

	public long getItemId(int position) {
		return position;
	}

	public View getView(final int position, View view, ViewGroup arg2) {
		ViewHolder viewHolder = null;
		if(view == null){
			viewHolder = new ViewHolder();
			view = LayoutInflater.from(context).inflate(R.layout.removable_list_item, null);
			viewHolder.tvTitle = (TextView) view.findViewById(R.id.list_item_title);
			viewHolder.btnDel = (Button) view.findViewById(R.id.list_item_delete);
			view.setTag(viewHolder);
		} else {
			viewHolder = (ViewHolder) view.getTag();
		}
		
		view.setOnTouchListener(new View.OnTouchListener() {
			
			public boolean onTouch(View v, MotionEvent event) {
				ViewHolder viewHolder = (ViewHolder) v.getTag();
				if(event.getAction() == MotionEvent.ACTION_DOWN){
					x = event.getX();
					if(curbutton != null){
						curbutton.setVisibility(View.GONE);
					}
				}
				else if (event.getAction() == MotionEvent.ACTION_UP){
					
				} else if (event.getAction() == MotionEvent.ACTION_MOVE){
					ux = event.getX();
					if(viewHolder.btnDel != null){
						if(x-ux > 20){
							viewHolder.btnDel.setVisibility(View.VISIBLE);
							curbutton = viewHolder.btnDel;
						}
					}
				} else {
				}
				return true;
			}
		});
		
		viewHolder.tvTitle.setText(this.arrays.get(position).getName()+"-"+this.arrays.get(position).getEmail());
		if(position == selectedpos){
			view.setBackgroundResource(R.drawable.white);
		} else {
			view.setBackgroundResource(R.drawable.black);
		}
		viewHolder.btnDel.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				if(curbutton != null){
					curbutton.setVisibility(View.GONE);
					arrays.remove(position);
					selectedpos = -1;
					PersonInfo p = arrays.get(position);
					helper.delete(p.getId());
					notifyDataSetChanged();
				}
			}
		});
		
		return view;
	}
	
	public class ViewHolder{
		TextView tvTitle;
		Button btnDel;
	}

}
